package cn.edu.baiyunu.myapplication.di

import android.content.Context
import androidx.room.Room
import androidx.room.migration.Migration
import androidx.sqlite.db.SupportSQLiteDatabase
import cn.edu.baiyunu.myapplication.data.dao.CategoryDao
import cn.edu.baiyunu.myapplication.data.dao.SavingsGoalDao
import cn.edu.baiyunu.myapplication.data.dao.SettingsDao
import cn.edu.baiyunu.myapplication.data.dao.TransactionDao
import cn.edu.baiyunu.myapplication.data.database.AppDatabase
import dagger.Module
import dagger.Provides
import dagger.hilt.InstallIn
import dagger.hilt.android.qualifiers.ApplicationContext
import dagger.hilt.components.SingletonComponent
import javax.inject.Singleton

/**
 * 提供数据库相关依赖的Hilt模块
 */
@Module
@InstallIn(SingletonComponent::class)
object DatabaseModule {
    
    // 数据库版本1到版本2的迁移
    private val MIGRATION_1_2 = object : Migration(1, 2) {
        override fun migrate(database: SupportSQLiteDatabase) {
            // 创建savings_goals表
            database.execSQL(
                "CREATE TABLE IF NOT EXISTS `savings_goals` (" +
                    "`id` TEXT NOT NULL, " +
                    "`name` TEXT NOT NULL, " +
                    "`targetAmount` REAL NOT NULL, " +
                    "`savingRate` REAL NOT NULL, " +
                    "`icon` TEXT NOT NULL, " +
                    "`type` TEXT NOT NULL, " +
                    "PRIMARY KEY(`id`)" +
                    ")"
            )
        }
    }
    
    /**
     * 提供数据库实例
     */
    @Provides
    @Singleton
    fun provideAppDatabase(
        @ApplicationContext context: Context
    ): AppDatabase {
        return Room.databaseBuilder(
            context,
            AppDatabase::class.java,
            "budget-database"
        )
            .addMigrations(MIGRATION_1_2)
            .build()
    }
    
    /**
     * 提供交易DAO
     */
    @Provides
    fun provideTransactionDao(appDatabase: AppDatabase): TransactionDao {
        return appDatabase.transactionDao()
    }
    
    /**
     * 提供分类DAO
     */
    @Provides
    fun provideCategoryDao(appDatabase: AppDatabase): CategoryDao {
        return appDatabase.categoryDao()
    }
    
    /**
     * 提供设置DAO
     */
    @Provides
    fun provideSettingsDao(appDatabase: AppDatabase): SettingsDao {
        return appDatabase.settingsDao()
    }
    
    @Provides
    fun provideSavingsGoalDao(appDatabase: AppDatabase): SavingsGoalDao {
        return appDatabase.savingsGoalDao()
    }
} 